#!/usr/bin/python

import re
import sys
import codecs
import threading
import collections

sys.path.append('..')
import xmpppy as xmpp
from templates import *

CONFIG_FILE = 'config.txt'
USERS_FILE = 'users.jid'
LOG_FILE = 'chats.log'

COMMAND_PREFIX = '/'
REPLY_PREFIX = '~ '
ENCODING = 'utf-8'
TIMEOUT = 30.0


class ConfBot(threading.Thread):

	def __init__(self, configFilename):
		threading.Thread.__init__(self)

		self.guests = []
		self.admins = []
		self.bots = []



	def process_Command(self.dispatcher, senderJID, command):
		global guests
		command = command.split()
		cmd = command[0]

# USER COMMANDS SECTION

		if cmd == 'help':
			reply = USER_HELP_MSG

		elif cmd == 'list':
			adminList = []
			guestList = []
			for attendee in attendees:
				if attendee in admins:
					adminList.append(attendee)
				else:
					guestList.append(attendee)
			reply = LIST_MSG % ('\n'.join(guestList), '\n'.join(adminList))
	
	elif cmd == 'leave':
		broadcast_Message(dispatcher, '', 'system', USER_LEFT_MSG % (senderJID, 'manual'))
		dispatcher.send(xmpp.Message(senderJID, USER_LEFT_MSG2))
		attendees.remove(senderJID)
		return

	elif senderJID not in admins:
		reply = USER_HELP_MSG

# ADMIN COMMANDS SECTION

	elif cmd == 'admin':
		reply = ADMIN_HELP_MSG

	elif cmd == 'status':
		if len(command) > 1:
			presence = xmpp.protocol.Presence()
			presence.setStatus(' '.join(command[1:]))
			client.send(presence)
			return
		else:
			reply = STATUS_USAGE_MSG

	elif cmd == 'exit':
		sys.exit(0)

	else:
		reply = ADMIN_HELP_MSG
	
	client.send(xmpp.Message(senderJID, reply))


	def broadcast_Message(dispatcher, senderJID, senderNode, message):
		message = '%s<%s> %s' % (REPLY_PREFIX, senderNode, message)
		lf = codecs.open(LOG_FILE, 'at', encoding=ENCODING)
		lf.write('%s\n' % message)
		lf.close()
		for attendee in attendees:
			if attendee != senderJID:
				dispatcher.send(xmpp.Message(attendee, message))


	def handle_Message(dispatcher, message):
		"Processes commands and chat messages"
		request = message.getBody()
		if request:
			sender = message.getFrom()
			senderJID = sender.getStripped()
			if request.startswith(REPLY_PREFIX):	# Ignore echo messages
				return
			if senderJID not in attendees:
				attendees.append(senderJID)
				broadcast_Message(dispatcher, '', 'system', USER_JOINED_MSG % senderJID)
			activeUsers.add(senderJID)
		request = request.strip()
		if request.startswith(COMMAND_PREFIX) and len(request) > 0:
			process_Command(client, senderJID, request[1:])
		else:
			broadcast_Message(dispatcher, senderJID, sender.getNode() , request)


	def handle_Presence(dispatcher, presence):
		"Automatically accepts user subscriptions"
		global roster
	senderJID = (presence.getFrom()).getStripped()
	type = presence.getType()

	if type == 'subscribe':			# Allow all subscribers
		roster.Authorize(senderJID)
		dispatcher.send(xmpp.Message(senderJID, WELCOME_MSG))
		broadcast_Message(dispatcher, '', 'system', SUBSCRIBED_MSG % senderJID)
		uf = codecs.open(USERS_FILE, 'at', encoding=ENCODING)
		uf.write('%s\n' % senderJID)
		uf.close()

	elif type == 'unavailable':		# Remove from the list if offline
		if senderJID in attendees:
			broadcast_Message(dispatcher, '', system, USER_LEFT_MSG % senderJID)
			attendees.remove(senderJID)


	def setup_Connection(self):
		global client, roster, contacts
		self.xmpp = xmpp.Client(domain, debug=[])
		self.xmpp.connect(server = (url, port))
		self.xmpp.auth(username, password)
		self.xmpp.sendInitPresence()
		self.roster = client.getRoster()
		self.xmpp.RegisterHandler('message', handle_Message)
		self.xmpp.RegisterHandler('presence', handle_Presence)


	def run(self):
		pass
